//
//  MeViewController.m
//  IBaby
//
//  Created by ZengYuan on 14/11/24.
//  Copyright (c) 2014年 com.zhongwei. All rights reserved.
//

#import "MeViewController.h"
#import "SettingCell.h"
//#import "MobClick.h"
#import "AppDelegate.h"
//#import "UserUnit.h"
#import "InfoViewController.h"
#import "PhotoCell.h"
#import "UserUnit.h"
#import "ModifyPasswdViewController.h"
#import "GeneralViewController.h"

@interface MeViewController ()
{
    //    JKUnit *jkunit;
//    NSString *token;
}
@end

@implementation MeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
  
    self.firstControllerInTabController = YES;
    // Do any additional setup after loading the view.
    
    CGRect rect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - self.navigationController.navigationBar.frame.size.height - self.tabBarController.tabBar.frame.size.height);
    
    tableView = [[UITableView alloc]initWithFrame:rect
                            style:UITableViewStylePlain];
      tableView.backgroundColor = MAIN_DARKCOLOR;
    tableView.delegate=self;
    tableView.dataSource=self;
    tableView.backgroundColor=[UIColor clearColor];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableView];
    
//    tableView.contentOffset = CGPointMake(0, 20);

    dataArray=[NSArray arrayWithObjects:
              [NSArray arrayWithObjects:@"头像", nil],
              [NSArray arrayWithObjects:@"修改密码",@"设置",@"关于我们",nil],
               nil];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.titleLabel.text=@"我的";
    
    //    self.navigationItem.title=@"设置";
    
//    self.backBtnPar.hidden=NO;
//    [self.backBtnPar setFrame:CGRectMake(0, 0, 30, 30)];
//    [self.backBtnPar setImage:[UIImage imageNamed:@"icon_left_h"] forState:UIControlStateHighlighted];
//    [self.backBtnPar setImage:[UIImage imageNamed:@"icon_left_default"] forState:UIControlStateNormal];

    [tableView reloadData];
}

//-(void)navLeftAction{
//    [self slideToLeftDrawer];
//}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    if(section == 0){
//        return 1;
//    }else{
        NSArray *array = dataArray[section];
        return [array count];
//    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return section==0?0:20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        return 80*VECTOR_IPHONE6;
    }
    
    return 60*VECTOR_IPHONE6;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//    return 0;
    if(section==0){
        return 0;
    }else{
        return 80;
    }
}


- (UIView *)tableView:(UITableView *)_tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 20)];
    return view;
}

- (UIView *)tableView:(UITableView *)atableView viewForFooterInSection:(NSInteger)section{
    
    
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 80)];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [view addSubview:btn];
    //    float x=(view.frame.size.width - 265)/2;
    float y=(view.frame.size.height - 42)/2;
    [btn setFrame:CGRectMake(28, y, view.frame.size.width-28*2, 42)];
    [btn addTarget:self action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
    
    [btn setBackgroundColor:GREEN_COLOR];
//    [self setBtnGreenBackgroundImage:btn];
    //    UIEdgeInsets insets = UIEdgeInsetsMake(0, 50, 0, 50);
    //    UIImage *streImage = [[UIImage imageNamed:@"redbtn_bk"] resizableImageWithCapInsets:insets];
    //    [btn setBackgroundImage:[UIImage imageNamed:@"redbtn_bk"]  forState:UIControlStateNormal];
    //    [btn setBackgroundImage:[UIImage imageNamed:@"redbtn_bk_h"]  forState:UIControlStateHighlighted];
    
    [btn setTitle:@"注销账号" forState:UIControlStateNormal];
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        static NSString *CellPhoto = @"CellPhoto";
        PhotoCell *cell=[_tableView dequeueReusableCellWithIdentifier:CellPhoto];
        if (!cell) {
            cell=[[[NSBundle mainBundle] loadNibNamed:@"PhotoCell" owner:self options:nil] objectAtIndex:0];
            [cell addBottomLine];
        }
        
        UserUnit *jkunit=[UserUnit getActiveUser];
//        NSString *url = nil;

//        [cell.photoImgView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"head"]];
        
        
        cell.nameLabel.text = [jkunit.userName length]?jkunit.userName:@"未设置";
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor whiteColor];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.rowType = [self rowIndex:indexPath];
        
        return cell;
        
    }else{
        
        static NSString *CellActivity = @"CellActivity";
        SettingCell *cell=[_tableView dequeueReusableCellWithIdentifier:CellActivity];
        if (!cell) {
            cell=[[SettingCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellActivity];
            
        }
        cell.backgroundColor=[UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        NSArray *array = dataArray[indexPath.section];
        cell.rowType = [self rowIndex:indexPath];
        cell.textLabel.text=[array objectAtIndex:indexPath.row];
//        cell.textLabel.font=[UIFont systemFontOfSize:15];

        cell.imageView.image = [UIImage imageNamed:[array objectAtIndex:indexPath.row]];
//        if (indexPath.section==3) {
////            cell.textLabel.text=@"注销账号";
//            
//            CGRect rect = cell.textLabel.frame;
//            rect.size.width = tableView.frame.size.width;
//            cell.textLabel.frame=rect;
//            cell.textLabel.textAlignment= NSTextAlignmentCenter;
//            cell.rowType = 2;
//
//        }
        

        
        return cell;

        
    }
    
  }

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            
            InfoViewController *ivc = [[InfoViewController alloc]init];
            ivc.hidesBottomBarWhenPushed=YES;
            [self.navigationController pushViewController:ivc animated:YES];
        }
    }
    
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            ModifyPasswdViewController *modifyvc = [[ModifyPasswdViewController alloc]init];
            modifyvc.hidesBottomBarWhenPushed=YES;
            [self.navigationController pushViewController:modifyvc animated:YES];
        }
        else if (indexPath.row == 1) {
            GeneralViewController *gvc = [[GeneralViewController alloc]init];
            gvc.hidesBottomBarWhenPushed=YES;
            [self.navigationController pushViewController:gvc animated:YES];
        }
    }

}
-(void)checkUpdate{
    Reachability*rea= [Reachability reachabilityForInternetConnection];
    {
        if ([rea isReachable]){
            [MobClick checkUpdateWithDelegate:self selector:@selector(callBackSelectorWithDictionary:)];
        }else{
            MBALERT(HTTPERROR_CANNOTREACH);
        }
    }
    
    
    
}

-(void)callBackSelectorWithDictionary:(NSDictionary *)dic{
    NSLog(@"%@", dic);
    BOOL needUpdate = [[dic objectForKey:@"update"] boolValue];
    
    if (needUpdate) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"爱维宝贝有新版本发布了，是否立即更新～" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: @"取消",@"更新", nil];
        alert.tag=177;
        [alert show];
    }else{
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"当前已经是最新版～" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        alert.tag=177;
//        [alert show];
        
        MBALERT(@"当前已经是最新版～");
        
    }
    
}

-(int)rowIndex:(NSIndexPath *)indexPath{
    NSArray *array = dataArray[indexPath.section];

    NSUInteger rowsCount = [array count];
    
    if (rowsCount>1) {
        if (indexPath.row==0) {
            return 1;
        }else if(indexPath.row == rowsCount-1){
            return 3;
        }
        return 2;
        
    }else{
        return 0;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)logout{
    
    
    UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"注销账号" message:@"注销账号，将会清除您的登录信息，确定吗" delegate:self cancelButtonTitle:nil otherButtonTitles:@"取消", @"确定",nil];
    [alertview show];
    alertview.tag=300;
    
    
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 300 && buttonIndex==1) {
        
        [UserUnit removeActiveUser];
        
        AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [delegate addRootViewController];
        
    }else if (alertView.tag == 177 && buttonIndex==1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:APPSTORE_URL]];
    }
}



/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


/*
-(void)requestRongyunToken{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        
        self.jkunit=[JKUnit getJKUnit];
        
        if(!self.jkunit){
            NSString *request = [NSString stringWithFormat:@"{\"%@\":%d}", JK_MESSAGE_TYPE,PARENT_GET_SELT_INFO];
            NSString *response;
            int tag =  [ZhongweiLib GetResponseByRequestShortConnectionServer:JK_USER_INFO_PROCESS request:request response:&response];
            if (tag == 0) {
                
                
                NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding];
                NSError *error = nil;
                id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
                if (jsonObject) {
                    [[NSUserDefaults standardUserDefaults] setObject:response forKey:@"JKUNIT_JSON"];
                    
                    NSDictionary*parent_info = [jsonObject objectForKey:JK_PARENT_INFO];
                    self.jkunit = [[JKUnit alloc]init];
                    self.jkunit.jk_parent_uuid = [parent_info objectForKey:JK_PARENT_UUID];
                    self.jkunit.jk_parent_phone = [parent_info objectForKey:JK_PARENT_PHONE];
                    self.jkunit.jk_parent_mail = [parent_info objectForKey:JK_PARENT_MAIL];
                    self.jkunit.jk_parent_name = [parent_info objectForKey:JK_PARENT_NAME];
                    self.jkunit.jk_parent_sex = [parent_info objectForKey:JK_PARENT_SEX];
                }
            }
        }
        
        
        NSString*url=nil;
#ifdef DEBUG
        url= URL_RONGYUNTOKEN_DEVELOP;
#else
        url= URL_RONGYUNTOKEN;
#endif

        
        //此处进行GET方式 发送http请求
        NSString *urlString =[NSString stringWithFormat:url, self.jkunit.jk_parent_uuid, [self.jkunit.jk_parent_name URLEncodedString], @""];
        
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
        [request setHTTPMethod:@"GET"];  //POST
        
        NSHTTPURLResponse *urlResponse = nil;
        NSError*error=nil;
        NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                                   returningResponse:&urlResponse error:&error];
        if (returnData) {
            id jsonObject = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingAllowFragments error:&error];
            NSLog(@"jsonObject = %@", jsonObject);
            if (jsonObject) {
                token = [jsonObject objectForKey:@"token"];
            }
        }
        
    });
}
*/

 


@end
